package com.daidai.controller;

import com.daidai.domain.Book;
import com.daidai.exception.BussinessException;
import com.daidai.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/books")
public class BookDaoController {

    @Autowired
    private BookService bookService;

    @PostMapping
    public Result addBook(@RequestBody Book book){
        Integer flag = bookService.saveBook(book);
        Result result = new Result();
        result.setCode(flag>0 ? Code.SAVE_OK : Code.SAVE_ERR);
        result.setMsg(flag > 0 ? "add成功" : "add失败");
        return result;
    }

    @DeleteMapping("/{id}")
    public Result deleteBook(@PathVariable Integer id){
        Integer flag = bookService.deleteBook(id);
        Result result = new Result();
        result.setCode(flag > 0 ? Code.DELETE_OK : Code.DELETE_ERR);
        result.setMsg(flag > 0 ? "删除成功":"删除失败");
        return result;
    }

    @PutMapping
    public Result updateBook(@RequestBody Book book){
        Integer flag = bookService.updateBook(book);
        Result result = new Result();
        result.setCode(flag > 0 ? Code.UPDATE_OK:Code.UPDATE_ERR);
        result.setData(book);
        result.setMsg(flag > 0 ? "更新成功":"更新失败");
        return result;
    }

    @GetMapping("/{id}")
    public Result getBookById(@PathVariable Integer id){

        if (id == 1){
            throw new BussinessException(Code.BUSINESS_ERR, "不要访问1");
        }

        Book book = bookService.getBookById(id);
        Result result = new Result();
        result.setCode(book != null ? Code.GET_OK:Code.GET_ERR);
        result.setData(book);
        result.setMsg(book != null ? "查询成功":"查询失败");
        return result;
    }

    @GetMapping
    public Result getAllBooks(){
        List<Book> books = bookService.getAllBooks();
        return new Result(
                books,
                books.size() > 0 ? Code.GET_OK : Code.GET_ERR,
                books.size() > 0 ? "查询成功" : "查询失败"
        );
    }

}
